<?php
class MiscModule
{
    public function share_record(){
        global $_FANWE;
        $uid = intval($_REQUEST['uid']);
        $res = FDB::fetchAll("SELECT * FROM ml_wogu_coupon_invite WHERE inviter ={$uid} order  by id desc");
        foreach ($res as $key => $value) {
            $res[$key]['addtime'] = date("Y-m-d H:i:s",$value['addtime']);
            $res[$key]['mobile'] = substr_replace($value['mobile'],'********',0,8);
        }
        echo json_encode($res);
    }

    public function anlired_share() {
        global $_FANWE;
        if($_POST['dosubmit']){
            $mobile = intval($_POST['mobile']);
            if(!$mobile) exit("请输入手机号");
            if(strlen($mobile)!=11) exit("请输入正确的手机号码");
            //该手机号码是否已经存在
            $uid = intval($_REQUEST['uid']);
            $res = FDB::fetchAll("SELECT * FROM ml_wogu_coupon_invite WHERE mobile={$mobile} AND inviter ={$uid}");
            if($res) exit("该手机号已邀请");
            FDB::insert('wogu_coupon_invite', array(
                'mobile' => $mobile,
                'inviter' => $uid,
                'addtime' => time(),
            ));
            exit("提交成功");
        }

        $uid = intval($_REQUEST['uid']);
        if($_REQUEST['download']){
            include template('page/misc/download');
        }else{
            include template('page/misc/anlired_share');
        }
        display($cache_file);
    }

	public function verify()
	{
		global $_FANWE;

		$seccode = random(6, 1);
		$seccodeunits = '';
		$s = sprintf('%04s', base_convert($seccode, 10, 24));
		$seccodeunits = 'BCEFGHJKMPQRTVWXY2346789';

		$seccode = '';
		for($i = 0; $i < 4; $i++)
		{
			$unit = ord($s{$i});
			$seccode .= ($unit >= 0x30 && $unit <= 0x39) ? $seccodeunits[$unit - 0x30] : $seccodeunits[$unit - 0x57];
		}

		$rhash = $_FANWE['request']['rhash'];

		fSetCookie('verify'.$rhash, authcode(strtoupper($seccode)."\t".(TIME_UTC - 180)."\t".$rhash."\t".FORM_HASH, 'ENCODE', $_FANWE['config']['security']['authkey']), 0, 1, true);

		@header("Expires: -1");
		@header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
		@header("Pragma: no-cache");

		require fimport('class/verify');

		$verify = new Verify();
		$verify->code = $seccode;
		$verify->width = 100;
		$verify->height = 36;
		$verify->display();
	}

	public function checknotice() {
	    global $_FANWE;
		$sql = 'SELECT * FROM '.FDB::table('user_notice').' WHERE uid='.$_FANWE['uid'];
		$r = FDB::fetchAll($sql);
        $res = FDB::query("SELECT * FROM ml_wogu_wxmessage_recent WHERE to_uid={$_FANWE['uid']} AND is_notify=0");
        $num = 0;
        while($v = FDB::fetch($res)) {
            $num += $v['msg_num'];
        }
        $r[] = array(
            'uid' => $_FANWE['uid'],
            'type' => 7,
            'num' => $num,
            'create_time' => time()
        );

		echo json_encode($r);
	}

	public function getusers() {
	    global $_FANWE;
	    $home_uid = intval($_GET['homeuid']);
        $sql = 'SELECT * FROM '.FDB::table('user_follow').' WHERE f_uid='.$home_uid;
        $follows = FDB::fetchAll($sql);
        $hisfollows = array();
        do {
            $len = count($follows);
            if($len > 0) {
                $index = rand(0, $len - 1);
                $sql = 'SELECT u.* FROM '.FDB::table('user_follow').' uf INNER JOIN '.FDB::table('user').' u ON u.uid=uf.uid WHERE uf.f_uid='.$follows[$index]['uid'] . ' AND uf.uid!='.$home_uid.' LIMIT 0,6';
                $hisfollows = FDB::fetchAll($sql);
                $sql = 'SELECT * FROM '.FDB::table('user_follow').' WHERE f_uid='.$_FANWE['uid'];
                $myfollows = FDB::fetchAll($sql);
                foreach($hisfollows as $k => $v) {
                    foreach($myfollows as $v1) {
                        if($v['uid'] == $v1['uid']) {
                            unset($hisfollows[$k]);
                        }
                    }
                }
                if(count($hisfollows) > 0) break;
                else {
                    unset($follows[$index]);
                    sort($follows);
                }
            }
        } while($len > 0);

        if(empty($hisfollows)) {
            exit('');
        } else
            include template('inc/u/u_me_list_getusers');
	}

	public function atusers() {
	    global $_FANWE;
	    //var_dump($_FANWE['user']['atusers']);
	    $data = array();
	    if(!empty($_FANWE['user']['atusers'])) {
	        $sql = 'SELECT uid,user_name FROM '.FDB::table('user').' WHERE uid IN('.$_FANWE['user']['atusers'].')';
	        $data = FDB::fetchAll($sql);
	    }

        echo json_encode($data);
	}

	public function contact() {
	    global $_FANWE;

		$cache_file = getTplCache('page/misc/contact');
		if(!@include($cache_file)) {
			include template('page/misc/contact');
		}

        display($cache_file);
	}

	public function feedback() {
	    global $_FANWE;

        $content = htmlspecialchars(trim($_POST['content']));
        $contact = htmlspecialchars(trim($_POST['contact']));
        if(empty($content)) exit('2');
        if(empty($contact)) exit('3');
        FDB::insert('wogu_feedback2', array(
            'content' => $content,
            'contact' => $contact,
            'dateline' => time()
        ));
        exit('1');
	}

	public function payintro() {
	    global $_FANWE;

		$cache_file = getTplCache('page/misc/payintro');
		if(!@include($cache_file)) {
			include template('page/misc/payintro');
		}

        display($cache_file);
	}

    public function catinfo() {
        global $_FANWE;

        $cate_id = intval($_GET['cate']);
        if(!$cate_id) exit;
        if(!isset($_FANWE['cache']['goods_category']['all'][$cate_id])) exit;
        $cateinfo = $_FANWE['cache']['goods_category']['all'][$cate_id];
        $childs = $children = $unsel_children = array();
        if(!empty($cateinfo['childs'])) {
            foreach ($cateinfo['childs'] as $cid) {
                $child = $_FANWE['cache']['goods_category']['all'][$cid];
                if($child['cate_type'] != $cateinfo['cate_type']) continue;

                if($cate_id != 311 || !isset($_SESSION['cityname']) || false !== strpos($child['cate_name'], $_SESSION['cityname'])) {
                    $childs[$cid] = array(
                        'id' => $cid,
                        'cate_type' => $child['cate_type'],
                        'cate_name' => $child['cate_name'],
                        'anli' => $child['anli'],
                    );

                    $children[] = $childs[$cid];
                } else {
                    $unsel_children[] = array(
                        'id' => $cid,
                        'cate_type' => $child['cate_type'],
                        'cate_name' => $child['cate_name'],
                        'anli' => $child['anli'],
                    );
                }
            }

            $childs = array_chunk($childs, 5);
            $childs = array_chunk($childs, 2);
        }
//print_r($childs);exit;
        exit(json_encode(array(
            'cateinfo' => $cateinfo,
            'childs' => $childs,
            'children' => $children,
            'unsel_children' => $unsel_children
        )));
    }

    public function getcatdata() {
        global $_FANWE;
        $cate_id = intval($_GET['cate']);
        $appconfig = include './public/app.php';

        if(!$cate_id || !isset($_FANWE['cache']['goods_category']['all'][$cate_id])) exit;
        $cateinfo = $_FANWE['cache']['goods_category']['all'][$cate_id];
        $ids = $appconfig[$cate_id]['ids'];

        require FANWE_ROOT.'core/function/wogu.func.php';
        $list = array();
        if($cateinfo['cate_type'] == 0) { // 文章
            $cateinfo['moblist'] = 'art';

            if(!empty($ids)) {
                //$sql = 'SELECT * FROM '.FDB::table('article').' WHERE mob_index=1 AND cate_id IN('.implode(',', $cateinfo['child']).') LIMIT 3';
                $sql = 'SELECT * FROM '.FDB::table('article').' WHERE id IN('.implode(',', $ids).') LIMIT 3';
                $list = FDB::fetchAll($sql);
                foreach ($list as $key => $value) {
                    if($value['uid']) {
                        $uids[] = $value['uid'];
                    }
                }
                $uids = array_unique($uids);
                $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid IN ('.implode(',', $uids).')';
                $tmp = FDB::fetchAll($sql);
                $name_list = array();
                foreach ($tmp as $key => $value) {
                    $name_list[$value['uid']] = $value;
                }

                foreach ($list as $key => $value) {
                    $list[$key]['author'] = empty($value['uid']) ? '火锅阁' : $name_list[$value['uid']]['user_name'];
                    $list[$key]['create_time_show'] = date('m.d', $value['create_time']);
                    $list[$key]['img'] = create_mob_img($value['img']);
                }
            }
        } elseif($cateinfo['cate_type'] == 1) { // 产品
            $cateinfo['moblist'] = 'product';

            if(!empty($ids)) {
                //$sql = 'SELECT * FROM '.FDB::table('wogu_product').' WHERE mob_index=1 AND cate_id IN('.implode(',', $cateinfo['child']).') LIMIT 3';
                $sql = 'SELECT * FROM '.FDB::table('wogu_product').' WHERE id IN('.implode(',', $ids).') LIMIT 3';
                $list = FDB::fetchAll($sql);
                foreach ($list as $key => $value) {
                    $list[$key]['img'] = create_mob_img($value['img']);
                }
            }
        } elseif($cateinfo['cate_type'] == 3) { // 商家资料
            $cateinfo['moblist'] = 'shopinfo';

            if(!empty($ids)) {
                $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE id IN('.implode(',', $ids).') LIMIT 3';
                $list = FDB::fetchAll($sql);
                if(!empty($list)){
                    $cities = include './public/city.php';
                    foreach ($list as $key => $value) {
                        $list[$key]['province_show'] = $cities['all'][$value['province']]['name'];
                        $list[$key]['city_show'] = $cities['all'][$value['city']]['name'];
                        $list[$key]['img'] = create_mob_img($value['img']);
                    }
                }
            }
        }

        exit(json_encode(array(
            'list' => $list,
            'cateinfo' => $cateinfo
        )));
    }

    public function getcode() {
        if(!strlen($_GET['mobile']) == 11 || !is_numeric($_GET['mobile'])) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '错误的手机号码'
            )));
        }

        if(isset($_SESSION['code_time']) && time() < $_SESSION['code_time']) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '获取验证码过于频繁'
            )));
        }

        $sql = "SELECT * FROM ".FDB::table('user')." WHERE mobile='{$_GET['mobile']}'";
        $user_info = FDB::fetchFirst($sql);

        session_start();
        $_SESSION['mobile'] = $_GET['mobile'];
        $_SESSION['code'] = mrandom(6, '0123456789');
        $_SESSION['code_time'] = time() + 30;
        send_sms($_SESSION['mobile'], $_SESSION['code']);
        exit(json_encode(array(
            'status' => 0,
            'isreg' => empty($user_info)
        )));
    }

    public function qrcode() {
        $id = intval($_GET['orderid']);
        if(!$id) exit('1');
        $order = FDB::fetchFirst("SELECT * FROM ml_wogu_order WHERE id={$id} AND flag IN(2,3,4)");
        if(empty($order)) exit('2');
        if($order['flag'] == 2) {
            $orderid = $order['orderid'];
            $total_fee = $order['total_fee'] * 0.3;
        } elseif($order['flag'] == 3) {
            $orderid = get_orderid2($order['orderid'], 3);
            $total_fee = $order['total_fee'] * 0.5;
        } else {
            $orderid = get_orderid2($order['orderid'], 4);
            $total_fee = $order['total_fee'] * 0.2;
        }

//echo $orderid;exit;
        $qr = new AbcQrcode();
        $url = $qr->genQrcode($orderid, $total_fee);
        if(empty($url)) exit;

        require './core/include/phpqrcode/qrlib.php';
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 7;//生成图片大小
        echo QRcode::png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
    }

    public function realname_pay() {
        global $_FANWE; 

        $sql = 'SELECT * FROM '.FDB::table('wogu_order_bzj').' WHERE userid = ' . $_FANWE['uid'];
        $log = $r = FDB::fetchFirst($sql);
        if($log && $log['flag'] == 1) ajaxmsg2(1, '订单已支付');
        if($log) {
            $total_fee = $log['total_fee'];
            $orderid = $log['orderid'];
            $ordername = $log['ordername'];
            $total_v = $log['total_v'];
            $total_bzj = $log['total_bzj'];
        } else {
            $sql = 'SELECT * FROM '.FDB::table('wogu_realname_shop').' WHERE uid = ' . $_FANWE['uid'];
            $shop = $r = FDB::fetchFirst($sql);
            if($shop['is_pay'] == 1) ajaxmsg2(1, '请不要重复支付');
            if($shop['v2'] == 1) ajaxmsg2(1, '你的认证类型不需要缴费');
            $paymap = array(2 => 180, 3 => 999);
            $total_v = $paymap[$shop['v2']];
            $total_fee = $total_v;
            $total_bzj = $shop['bzj'];
            if($shop['v2'] == 3) {
                $total_fee += $total_bzj;
            } else {
                $total_bzj = 0;
            }

            $orderid = 'V'.date('Ymdhis');
            $ordername = "婚礼树V认证缴费";
            $oid = FDB::insert('wogu_order_bzj', array(
                'orderid' => $orderid,
                'ordername' => $ordername,
                'userid' => $_FANWE['uid'],
                'total_fee' => $total_fee,
                'total_v' => $total_v,
                'total_bzj' => $total_bzj,
                'v2' => $shop['v2'],
                'dateline' => time()
            ), true);
        }

        $qr = new AbcQrcode();
        $url = $qr->genQrcode($orderid, $total_fee);
        if(empty($url)) ajaxmsg2(1, '支付接口调用失败');

        require './core/include/phpqrcode/qrlib.php';
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 7;//生成图片大小
        $qrcodeFile = './public/qrcode/' . $orderid . '.png';
        QRcode::png($url, $qrcodeFile, $errorCorrectionLevel, $matrixPointSize, 2);

        ajaxmsg2(0, array(
            'qrcode' => $qrcodeFile,
            'total_fee' => $total_fee,
            'total_v' => $total_v,
            'total_bzj' => $total_bzj,
            'tip' => "{$total_v}元+{$total_bzj}元={$total_fee}元"
        ));
    }

    public function realname_check_orderstatus() {
        global $_FANWE; 

        $sql = 'SELECT * FROM '.FDB::table('wogu_order_bzj').' WHERE userid = ' . $_FANWE['uid'];
        $log = FDB::fetchFirst($sql);
        if($log && $log['flag'] == 1) ajaxmsg2(0, '订单已支付');
        ajaxmsg2(1, '订单未支付');
    }
}

function get_orderid2($orderid, $flag) {
    $orderid2 = '';
    $addon = $flag == 3 ? 1 : 2;
    for($i = 0; $i < strlen($orderid); $i++) {
        $val = intval($orderid[$i]) + $addon;
        $val = $val == 10 ? 'A' : ($val == 11 ? 'B' : $val);
        $orderid2 .= $val;
    }

    return $orderid2;
}

function mrandom($length, $chars = '0123456789') {
    $hash = '';
    $max = strlen($chars) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

function send_sms($mobile, $code) {
    $AppKey = '237ce43a07a28afe921e46978f30fd87';
    $AppSecret = 'dd33e1cee2d4';
    $Nonce = rand(100000,999999);
    $CurTime = time();
    $CheckSum = strtolower(sha1($AppSecret.$Nonce.$CurTime));
    $url = 'https://api.netease.im/sms/sendtemplate.action';
    $head_arr = array();
    $head_arr[] = 'Content-Type: application/x-www-form-urlencoded';
    $head_arr[] = 'charset: utf-8';
    $head_arr[] = 'AppKey:'.$AppKey;
    $head_arr[] = 'Nonce:'.$Nonce;
    $head_arr[] = 'CurTime:'.$CurTime;
    $head_arr[] = 'CheckSum:'.$CheckSum;
    $data = array();
    $data['templateid'] = '3030586';
    $data['mobiles'] = '["'.$mobile.'"]';
    $data['params'] = '["'.$code.'"]';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $head_arr);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    $result = curl_exec($ch);
    curl_close($ch);
    //var_dump($result);
    $resArr = json_decode($result, true);
    return isset($resArr['code']) && $resArr['code'] == 200;
}

class AbcQrcode
{
    const bankURL = "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain";
    const MERCHANTID = "105000048164065";
    const POSID = "021895869";
    const BRANCHID = "420000000";
    const RETURNTYPE = "3";
    const TIMEOUT = "";
    const CCB_IBSVersion = 'V6';

    public function genQrcode($orderid, $payment) {
        $curcode="01";
        $txcode = "530550";
        $remark1 = "";
        $remark2 = "";
        $pub32tr2 = "940b4f365a3a291b9a1756f1020111";

        $sign = $this->_getSign(array(
            'MERCHANTID' => self::MERCHANTID,
            'POSID' => self::POSID,
            'BRANCHID' => self::BRANCHID,
            'ORDERID' => $orderid,
            'PAYMENT' => $payment,
            'CURCODE' => $curcode,
            'TXCODE' => $txcode,
            'REMARK1' => $remark1,
            'REMARK2' => $remark2,
            'RETURNTYPE' => self::RETURNTYPE,
            'TIMEOUT' => self::TIMEOUT,
            'PUB' => $pub32tr2
        ));

        $data = array(
            'CCB_IBSVersion' => self::CCB_IBSVersion,
            'MERCHANTID' => self::MERCHANTID,
            'BRANCHID' => self::BRANCHID,
            'POSID' => self::POSID,
            'ORDERID' => $orderid,
            'PAYMENT' => $payment,
            'CURCODE' => $curcode,
            'TXCODE' => $txcode,
            'REMARK1' => $remark1,
            'REMARK2' => $remark2,
            'RETURNTYPE' => self::RETURNTYPE,
            'TIMEOUT' => self::TIMEOUT,
            'MAC' => $sign
        );

        $ret = http_post(self::bankURL, $this->_getURLParams($data));
        if(isset($ret['PAYURL'])) {
            $payInfoStr = file_get_contents($ret['PAYURL']);
            if(!empty($payInfoStr)) {
                $payInfo = json_decode($payInfoStr, true);
                if(isset($payInfo['QRURL'])) {
                    $qrurl = urldecode($payInfo['QRURL']);
                    return $qrurl;
                }
            }
        }
    }

    protected function _getURLParams($params) {
        $map = array();
        foreach ($params as $k => $v) {
            $map[] = "{$k}=$v";
        }

        return implode('&', $map);
    }

    protected function _getSign($params) {
        return md5($this->_getURLParams($params));
    }
}

function http_get($url, $raw = true) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 500);
    //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Linux; U; Android 5.0.2; zh-cn; Redmi Note 3 Build/LRX22G) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.100 U3/0.8.0 Mobile Safari/534.30 Nebula AlipayDefined(nt:WIFI,ws:360|640|3.0) AliApp(AP/10.0.1.123166) AlipayClient/10.0.1.123166 Language/zh-Hans useStatusBar/true");
    $data = curl_exec($ch);
    curl_close($ch);
    if(!$data)
        return false;

    return $raw ? $data : json_decode($data, true);
}

function http_post($url, $fields, $raw = false) {//echo $url;exit;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
    //curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
    $data = curl_exec($ch);//var_dump($data);
    curl_close($ch);

    if($data) {
        return $raw ? $data : json_decode($data, true);
    }

    return false;
}
